const cateBox = document.querySelector('.medi > .clearfix')
const listBox = document.querySelector('.list')
const pageBox = document.querySelector('.pageInfo')
const filterbox = document.querySelector('main')
const sorts = document.querySelectorAll('.sortItem > span')
const select = document.querySelector('select')


getCategoryList()
async function getCategoryList() {

  const res = await pAjax({
    url: 'http://localhost:8888/goods/category',
    dataType: 'json'
  })

  let str = ``
  res.list.forEach(item => {
    str += `<li class="cateItem">${ item }</li>`
  })

  cateBox.innerHTML = str
}


const listInfo = {
    current: 1,
    pagesize: 12,
    search: '',
    filter: '',
    saleType: 0,
    sortType: '',
    sortMethod: '',
    category: ''
  }

  const filterArr = []
  getGoodsList()
async function getGoodsList() {
  let data = ''
  for (let key in listInfo) {
    if (listInfo[key]) data += key + '=' + listInfo[key] + '&'
  }
  data = data.slice(0, -1)

  const res = await pAjax({
    url: 'http://localhost:8888/goods/list',
    data,
    dataType: 'json'
  })

  const { list, total } = res

  let str = ''
  list.forEach(item => {
    str += `
      <li data-id="${ item.goods_id }">
        <div class="show">
          <img src="${ item.img_big_logo }" alt="">
        </div>
        <div class="desc">
          <p class="info">${ item.title }</p>
          <p class="price">
            <span class="current">￥ ${ item.current_price }</span>
            <span class="old">￥ ${ item.price }</span>
          </p>
          <button data-id="${ item.goods_id }">直接购买</button>
        </div>
        <span class="tip ${ item.is_hot ? 'active' : '' }">HOT</span>
        <span class="tip ${ item.is_sale ? 'active' : '' }">SALE</span>
      </li>
    `
  })
  listBox.innerHTML = str

  pageBox.innerHTML = ` ${ listInfo.current } / ${ total } `
}


filterbox.addEventListener('click', e => {

    e = e || window.event
    const target = e.target || e.srcElement
  

    if (target.className === 'cateItem') {
      console.log('你点击的是分类内容')
      listInfo.category = target.innerText
      getGoodsList()

      for (let i = 0; i < cateBox.children.length; i++) {
        cateBox.children[i].classList.remove('active')
      }
      target.classList.add('active')
    }
  

    if (target.className.indexOf('filterItem') !== -1) {

      const type = target.dataset.type
      filterArr.push(type)

      listInfo.filter = [ ...new Set(filterArr) ].join(',')

      target.classList.add('active')

      getGoodsList()
    }
  

    if (target.className === 'searchBtn') {

      const searchText = target.previousElementSibling.value

      listInfo.search = searchText

      getGoodsList()
    }
  

    if (target.className === 'sortItem') {
      console.log('点击的是排序按钮')

      const type = target.dataset.type
      const method = target.dataset.method
  

      for (let i = 0; i < sorts.length; i++) {
        sorts[i].classList.remove('active')
      }

      if (method === 'ASC') {
        target.dataset.method = 'DESC'
        target.lastElementChild.classList.add('active')
      } else {
        target.dataset.method = 'ASC'
        target.firstElementChild.classList.add('active')
      }
  

      listInfo.sortType = type
      listInfo.sortMethod = method === 'ASC' ? 'DESC' : 'ASC'
  

      getGoodsList()
    }
  

    if (target.className === 'prev') {

      if (listInfo.current !== 1) listInfo.current--

      getGoodsList()
    }
  

    if (target.className === 'next_1') {

      listInfo.current++

      getGoodsList()
    }
  })
  

  select.addEventListener('change', () => {

    const pagesize = select.value

    listInfo.pagesize = pagesize
  

    getGoodsList()
  })
  


  listBox.addEventListener('click', async e => {
    e = e || window.event
    const target = e.target || e.srcElement
  
    // 判断点击的是 li 标签的类名
    if (target.tagName === 'LI') {
      // 在跳转页面的时候, 最好把商品id 带到新的详情页面
      const id = target.dataset.id
      // 存储在 sessionStorage 里面
      window.sessionStorage.setItem('goods_id', id)
      // 跳转页面
      window.location.href = './detail.html'
    }
  
    // 4-2. 判断点击的是 加入购物车 按钮
    if (target.tagName === 'BUTTON') {
      // 4-2-1. 拿到 localStorage 内部是不是有 id 和 token
      // 如果没有, 去到登录页
      const id = window.localStorage.getItem('id')
      const token = window.localStorage.getItem('token')
  
      // 4-2-2. 判断 id 和 token 是否存在
      if (!id || !token) {
        const result = window.confirm('您还没有登录, 点击确定跳转到登录页, 点击取消稍后在购买 !')
        // 跳转之前, 标识一下 url 信息
        window.localStorage.setItem('url', 'list')
  
        // 跳转回到登录页
        if (result) window.location.href = './login.html'
        return
      }
  
      // 4-2-3. 拿到当前的商品 id
      const goodsId = target.dataset.id
  
      // 4-2-4. 发送请求加入购物车
      const res = await pAjax({
        url: 'http://localhost:8888/cart/add',
        token,
        data: `id=${id}&goodsId=${goodsId}`,
        method: 'post',
        dataType: 'json'
      })
      window.localStorage.setItem('url', 'http://localhost:8888/cart/add' )
      window.localStorage.setItem('data', `id=${id}&goodsId=${goodsId}` )
      window.localStorage.setItem('method', 'post' )
      window.localStorage.setItem('dataType', 'json' )
  
      // 4-2-4. 提示用户
      if (res.code === 1) window.alert('加入购物车成功了')
  
      // 4-2-5. 加入不成功的时候, 提示用户
    }
  })
  